package com.enqualcomm.kids.mvp.chat;


import android.media.MediaRecorder;

import java.io.File;

/**
 * Created by yinzhiqun on 2015/5/30.
 * 管理MediaRecorder
 */
public class RecorderManager extends AbstractRecorderManager implements MediaRecorder.OnInfoListener, MediaRecorder.OnErrorListener {

    private MediaRecorder mMediaRecorder;
    /**
     * 录音发生错误
     */
    private boolean hasError;

    private String mCurrentFilePath;

    public RecorderManager(){
        initMediaRecorder();
    }

    private void initMediaRecorder() {
        localRelease();
        mMediaRecorder = new MediaRecorder();
        mMediaRecorder.setOnInfoListener(this);
        mMediaRecorder.setOnErrorListener(this);
    }

    @Override
    protected void localRelease() {
        if (mMediaRecorder!=null){
            mMediaRecorder.setOnInfoListener(null);
            mMediaRecorder.setOnErrorListener(null);
//            mMediaRecorder.reset();
            mMediaRecorder.release();
            mMediaRecorder=null;
        }
        deleteCurrentFile();//极端情况下，没有停止播放，确要退出界面了，删除垃圾文件
    }

    @Override
    public void start(String path) {
        if (hasError){
            initMediaRecorder();
        }

        mCurrentFilePath = path;
        mMediaRecorder.reset();
        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
        mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        mMediaRecorder.setMaxDuration(RECORDER_MAX);//最长录音时间，单位毫秒

        try {
//            mMediaRecorder.setOutputFile(new FileOutputStream(path).getFD());
            mMediaRecorder.setOutputFile(path);
            mMediaRecorder.prepare();
            mMediaRecorder.start();
            notifyObservers(RecorderObserver.RECORDING);
        } catch (Exception e) {
            e.printStackTrace();

            //部分手机第二次录音（重复使用MediaRecorder对象）会报错
            if (!hasError){//防止死循环，第一次hasError：false，修改hasError：true，然后重新初始化并开始录音,再发生错误，不处理
                //第二次，直接就重新初始化（没必要等到抛出异常再重新初始化）
                hasError = true;
                start(path);
            }
        }
    }

    @Override
    public String stop() {
        //停止录音
        tryStop();
        notifyObservers(RecorderObserver.IDLE);

        String temp = mCurrentFilePath;
        mCurrentFilePath = null;
        return temp;
    }

    @Override
    public void cancel() {
        tryStop();
        notifyObservers(RecorderObserver.IDLE);

        //删除录音文件
        deleteCurrentFile();
    }

    @Override
    public void deleteCurrentFile() {
        if (mCurrentFilePath!=null){
            new File(mCurrentFilePath).delete();
            mCurrentFilePath = null;
        }
    }

    @Override
    public String getCurrentFilePath(){
        return mCurrentFilePath;
    }

    @Override
    public int getAmplitude() {
        if (mMediaRecorder != null)
            return mMediaRecorder.getMaxAmplitude();
        else
            return 0;
    }

    @Override
    public void onInfo(MediaRecorder mediaRecorder, int i, int i1) {
        notifyObservers(RecorderObserver.TIME_OUT);
        mCurrentFilePath = null;
    }

    @Override
    public void onError(MediaRecorder mediaRecorder, int i, int i1) {
        notifyObservers(RecorderObserver.ERROR);
        mCurrentFilePath = null;
    }

    private void tryStop(){
        if (mMediaRecorder!=null){
            try {
                mMediaRecorder.stop();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
